
import net from 'net'
import ExBuffer from 'ExBuffer'
import Url from 'url'

var Href = null

export default class Socket {
  constructor (Uri) {
    let uri = /^((https|http|ftp|rtsp|mms)?:\/\/)/.test(Uri) ? Uri : `rtsp://${Uri}`
    let { hostname, port } = Url.parse(uri)
    Href = { hostname, port }
  }

  send = (data, callback = null) => {
    let { hostname, port } = Href
    let socket = new net.Socket()
    let exBuffer = new ExBuffer().uint32Head().bigEndian()
    return new Promise((resolve, reject) => {
      // 连接 ...
      socket.connect(port, hostname, () => {
        try {
          socket.write(data)
        } catch (error) {
          reject(error)
        }
      })
      // 接收数据
      socket.on('data', data => {
        exBuffer.put(data)
      })
      // 拼接数据
      exBuffer.on('data', buffer => {
        if (buffer.length > 0) {
          try {
            resolve(buffer)
          } catch (error) {
            reject(error)
          }
          socket.destroy()
        }
      })
      // 错误处理
      socket.on('error', error => {
        reject(error)
      })
      // 关闭连接
      socket.on('close', () => {
        // console.log('close')
      })
    })
  }
}